//
//  ActivityNewViewController.m
//  TimeTracker
//
//  Created by Michael Flakus on 2/24/13.
//  Copyright (c) 2013 Michael Flakus. All rights reserved.
//

#import "ActivityNewViewController.h"

@interface ActivityNewViewController ()

@end

@implementation ActivityNewViewController


int selectedRow = -1;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	self.title = @"New Activity";
    
    // Configure the save button
	UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save)];
	self.navigationItem.rightBarButtonItem = saveButton;
    
    // Configure the cancel button
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel)];
	self.navigationItem.leftBarButtonItem = cancelButton;
    
    
    // create error message alert views
    _missingActivityNameError = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Activity Name cannot be blank" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    _missingCategoryError = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Category cannot be blank" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    // create input fields
    
    // activity name text field
    CGRect frame = CGRectMake(10.0, 50.0, 300.0, 28.0);
    _activityNameTextField = [[UITextField alloc] initWithFrame:frame];
    _activityNameTextField.borderStyle = UITextBorderStyleRoundedRect;
    _activityNameTextField.textColor = [UIColor blackColor];
    _activityNameTextField.font = [UIFont systemFontOfSize:17.0];
    //textField.placeholder = @"";
    _activityNameTextField.backgroundColor = [UIColor clearColor];
    _activityNameTextField.autocorrectionType = UITextAutocorrectionTypeYes;
    _activityNameTextField.keyboardType = UIKeyboardTypeDefault;
    _activityNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:_activityNameTextField];
    
    // new category
    CGRect frame2 = CGRectMake(10.0, 110.0, 300.0, 28.0);
    _categoryTextField = [[UITextField alloc] initWithFrame:frame2];
    _categoryTextField.borderStyle = UITextBorderStyleRoundedRect;
    _categoryTextField.textColor = [UIColor blackColor];
    _categoryTextField.font = [UIFont systemFontOfSize:17.0];
    _categoryTextField.backgroundColor = [UIColor clearColor];
    _categoryTextField.autocorrectionType = UITextAutocorrectionTypeYes;
    _categoryTextField.keyboardType = UIKeyboardTypeDefault;
    _categoryTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:_categoryTextField];
    
    // load category options from database
    
    NSLog(@"loading categories from database");
    
    // load data from database
    _categoryNames = [[NSMutableArray alloc] init];
    _categoryIds = [[NSMutableArray alloc] init];
    int row = 0;
    int selected_row = 0;
    
    
    // database lookups
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            // load all active categories
            
            // add special "New Category" option to picker as the first option
            [_categoryIds addObject:@"0"];
            [_categoryNames addObject:@"Add a New Category..."];
            
            NSString *select_categories = [NSString stringWithFormat:@"SELECT categories.id,categories.name from categories where categories.active = 1 order by categories.name"];
            const char *select_categories_const = [select_categories UTF8String];
            
            sqlite3_stmt *res_categories;
            if(sqlite3_prepare(_database, select_categories_const, -1, &res_categories, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement: %s",select_categories_const);
                NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
            }
            else
            {
                while (sqlite3_step(res_categories)==SQLITE_ROW) {
                    
                    NSLog(@"Found a category: %@",[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_categories,1)]);
                    
                    if([_categoryName isEqualToString:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_categories,1)]])
                    {
                        selected_row = row+1;
                    }
                    
                    [_categoryIds addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_categories,0)]];
                    [_categoryNames addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_categories,1)]];
                    
                    
                    row++;
                }
                sqlite3_finalize(res_categories);
            }
        }
        else
        {
            NSLog(@"Error: database could not be found in ActivityEditingViewController");
        }
    }
    
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }
    
    
    CGRect frame_picker = CGRectMake(0.0, 160.0, 320.0, 400.0);
    _categoryPickerView = [[UIPickerView alloc] initWithFrame:frame_picker];
    _categoryPickerView.delegate = self;
    _categoryPickerView.showsSelectionIndicator = YES;
    [_categoryPickerView selectRow:selected_row inComponent:0 animated:YES];
    [self.view addSubview:_categoryPickerView];
    
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


#pragma mark -
#pragma mark Save and cancel operations

- (IBAction)save {
	
    // update the current value in the databbase, then return to the previous view
    NSLog(@"activity name %@",_activityNameTextField.text);
    NSLog(@"update category with row: %@",_selectedCategoryID);
	NSLog(@"category name: %@",_categoryNames[selectedRow]);
    NSLog(@"category name text field: %@",_categoryTextField.text);
    
    // if activity name and category are both not empty, then create a new activity in the database, else display an alert error message to the user
    if(_activityNameTextField.text == NULL || [_activityNameTextField.text isEqualToString:@""])
        [_missingActivityNameError show];
    else if(_categoryTextField.text == NULL || [_categoryTextField.text isEqualToString:@""])
        [_missingCategoryError show];
    else
    {
        // update field
        @try {
            
            // connect to db
            
            NSString *docsDir;
            NSArray *dirPaths;
            
            // Get the documents directory
            dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            
            docsDir = dirPaths[0];
            
            // Build the path to the database file
            _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
            
            NSFileManager *filemgr = [NSFileManager defaultManager];
            
            // check to see if database already exists...
            if ([filemgr fileExistsAtPath: _databasePath ] == YES)
            {
                // open database
                if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
                {
                    NSLog(@"An error has occured when trying to open the database");
                }
                
                char *errMsg;
                
                // add new category, if necessary
                if([_selectedCategoryID intValue] == 0)
                {
                    // New Category needs to be saved first and then assigned to this activity
                    NSString *insert_category = [NSString stringWithFormat:@"INSERT INTO categories (name) VALUES ('%@')",_categoryTextField.text];
                    const char *insert_category_const = [insert_category UTF8String];
                    NSLog(@"insert query: %s",insert_category_const);
                    if (sqlite3_exec(_database, insert_category_const, NULL, NULL, &errMsg) != SQLITE_OK)
                        NSLog(@"Failed to insert category: %s",errMsg);
                    
                    // lookup id for newly added category
                    NSString *new_category_id = [NSString stringWithFormat:@"select id from categories where name = '%@'",_categoryTextField.text];
                    const char *new_category_id_const = [new_category_id UTF8String];
                    
                    sqlite3_stmt *res_new_category_id;
                    if(sqlite3_prepare(_database, new_category_id_const, -1, &res_new_category_id, NULL) != SQLITE_OK)
                    {
                        NSLog(@"Problem with prepare statement: %s",new_category_id_const);
                        NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
                    }
                    else
                    {
                        NSLog(@"query: %s",new_category_id_const);
                        
                        while (sqlite3_step(res_new_category_id)==SQLITE_ROW) {
                            _selectedCategoryID = [NSString stringWithUTF8String:(char *) sqlite3_column_text(res_new_category_id,0)];
                            break;
                        }
                        
                        sqlite3_finalize(res_new_category_id);
                    }
                }
                
                NSString *insert_sql = [NSString stringWithFormat:@"INSERT INTO activities (activity_name,category_id) VALUES ('%@','%@')",_activityNameTextField.text,_selectedCategoryID];
                const char *insert_const = [insert_sql UTF8String];
                sqlite3_stmt *res_insert;
                if(sqlite3_prepare(_database, insert_const, -1, &res_insert, NULL) != SQLITE_OK)
                {
                    NSLog(@"Problem with prepare statement: %s",insert_const);
                    NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
                }
                else
                {
                    NSLog(@"query: %s",insert_const);
                    if(SQLITE_DONE != sqlite3_step(res_insert))
                        NSAssert1(0, @"Error while inserting. '%s'", sqlite3_errmsg(_database));
                    
                    sqlite3_finalize(res_insert);
                }
            }
            else
            {
                NSLog(@"Error: database could not be found in ActivityNewViewController");
            }
        }
        
        @catch (NSException *exception) {
            NSLog(@"An exception occured: %@", [exception reason]);
        }
        @finally {
            // close the database connection
            sqlite3_close(_database);
        }
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
}


- (IBAction)cancel {
    // return to the previous view, without saving
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark -
#pragma mark Category Picker operations

- (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component {
    // Handle the selection
    selectedRow = row;
    if(row == 0)
    {
        NSLog(@"special NEW option selected");
        _selectedCategoryID = @"0";
        _categoryTextField.text = @"";
        _categoryTextField.enabled = YES;
        [_categoryTextField becomeFirstResponder];
    }
    else
    {
        // set label of selected category as text of category input field
        _selectedCategoryID = _categoryIds[row];
        _categoryTextField.text = _categoryNames[row];
        _categoryTextField.enabled = NO;
        [_categoryTextField resignFirstResponder];
    }
}

// tell the picker how many rows are available for a given component
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return _categoryIds.count;
}

// tell the picker how many components it will have
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

// tell the picker the title for a given component
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    // use row id to display associated label
    
    NSString *title;
    title = _categoryNames[row];
    
    return title;
}

// tell the picker the width of each row for a given component
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    int sectionWidth = 300;
    
    return sectionWidth;
}




@end
